package com.block.api.controller.expose;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.exception.ApiException;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.LogFactory;
import com.block.datapush.factory.PushApiFactory;
import com.block.db.entity.MerchantBaseInfo;
import com.block.merchant.service.IMatchUpdateStartLeveService;
import com.block.merchant.service.IMerchantBaseInfoService;
import com.block.merchant.service.infotype.MerchantApiBHandleService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("apinotice/merchant")
public class NoticeMerchantController {

    private static final Logger log = LogFactory.getNoticeMerLog();

    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    IMerchantBaseInfoService merchantBaseInfoService;
    @Autowired
    MerchantApiBHandleService merchantApiBHandleService;
    @Autowired
    IMatchUpdateStartLeveService matchUpdateStartLeveService;

    public static void main(String[] args) {

        String hostUrl = "https://api.longzankeji.cn";
        String hostUrlTest = "http://apitest.koukoudai.shop";
        String infoId = "105";
        System.out.println(StrUtil.format("{}/apinotice/merchant/notifyResult/{}", hostUrl, infoId));
        System.out.println(StrUtil.format("{}/apinotice/merchant/notifyEnter/{}", hostUrl, infoId));
        System.out.println(StrUtil.format("{}/apinotice/merchant/notifyPullData/{}", hostUrl, infoId));

        System.out.println(StrUtil.format("{}/apinotice/merchant/notifyResult/{}", hostUrlTest, infoId));
        System.out.println(StrUtil.format("{}/apinotice/merchant/notifyEnter/{}", hostUrlTest, infoId));
        System.out.println(StrUtil.format("{}/apinotice/merchant/notifyPullData/{}", hostUrlTest, infoId));

        /**
         * https://api.longzankeji.cn/apinotice/merchant/notifyResult/83
         *
         * https://api.longzankeji.cn/apinotice/merchant/notifyEnter/83
         */
    }

    /**
     * 授权结果通知
     *
     * @param request
     * @param infoId
     * @return
     */
    @RequestMapping(value = "/notifyResult/{infoId}", method = {RequestMethod.POST, RequestMethod.GET})
    public String notifyResult(HttpServletRequest request, @PathVariable("infoId") String infoId) {
        Map<String, String[]> parameterMap = null;
        String paramContent = null;
        try {
            parameterMap = request.getParameterMap();
            paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            log.info("【商户回调通知】【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);

            // 调用异步方法，获取返回的 CompletableFuture
            CompletableFuture<JSONObject> future = merchantApiBHandleService.noticePushDataResult(infoId, parameterMap, paramContent);

            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);
            // 根据请求对象，拿到请求数据
            JSONObject jsonObjectCallBack = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                    .getNoticeResultReturn(parameterMap, paramContent, new JSONObject());
            return JSON.toJSONString(jsonObjectCallBack);
        } catch (Exception exception) {
            String content = StrUtil.format("【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);
            notifyExceptionService.notifyNoticeInfo("MERCHANT_NOTICE_RESULT", "商户授权结果通知", content, exception);
        }
        return "exception";
    }

    /**
     * 进件通知
     *
     * @param request
     * @param infoId
     * @return
     */
    @RequestMapping(value = "/notifyEnter/{infoId}", method = {RequestMethod.POST, RequestMethod.GET})
    public String notifyEnter(HttpServletRequest request, @PathVariable("infoId") String infoId) throws IOException {

        Map<String, String[]> parameterMap = null;
        String paramContent = null;
        try {
            parameterMap = request.getParameterMap();
            paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            log.info("【商户进件通知】【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);

            JSONObject jsonObject = merchantApiBHandleService.noticeEnterPushData(infoId, parameterMap, paramContent);
            return JSON.toJSONString(jsonObject);
        } catch (Exception exception) {
            exception.printStackTrace();
            String content = StrUtil.format("【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);
            notifyExceptionService.notifyNoticeInfo("MERCHANT_NOTICE_ENTER", "商户进件通知", content, exception);
        }
        return "exception";
    }

    /**
     * 返回数据
     *
     * @param request
     * @param infoId
     * @return
     */
    @RequestMapping(value = "/notifyPullData/{infoId}", method = {RequestMethod.POST, RequestMethod.GET})
    public String notifyPullData(HttpServletRequest request, @PathVariable("infoId") String infoId) throws IOException {

        Map<String, String[]> parameterMap = null;
        String paramContent = null;
        try {
            parameterMap = request.getParameterMap();
            paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            log.info("【商户拉取通知】【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);

            JSONObject jsonObject = merchantApiBHandleService.noticePullData(infoId, parameterMap, paramContent);
            return JSON.toJSONString(jsonObject);
        } catch (Exception exception) {
            exception.printStackTrace();
            String content = StrUtil.format("【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);
            notifyExceptionService.notifyNoticeInfo("MERCHANT_PULL_DATA", "商户拉取通知", content, exception);
        }
        return "exception";
    }

    /**
     * 下游机构
     * 用户星级回传
     */
    @RequestMapping(value = "/updatestartlevel/{infoId}", method = {RequestMethod.POST})
    public String updateStartLevel(HttpServletRequest request,
                                   @PathVariable("infoId") Integer infoId) {

        Map<String, String[]> parameterMap = null;
        String paramContent = null;
        try {

            parameterMap = request.getParameterMap();
            paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            log.info("【用户星级回传】【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);

            JSONObject returnObject = matchUpdateStartLeveService.update1(infoId, parameterMap, paramContent);

            return returnObject.toJSONString();
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return "星级回传异常";
    }

}
